package com.gxuwz.medical.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.gxuwz.medical.config.Constant;
import com.gxuwz.medical.domain.menu.Menu;
import com.gxuwz.medical.domain.role.Role;
import com.gxuwz.medical.domain.user.User;
import com.gxuwz.medical.domain.weixin.MobileApiEntity;
import com.gxuwz.medical.exception.UserNotFoundException;
import com.gxuwz.medical.tool.PasswordUtil;
import com.gxuwz.medical.web.listener.MySessionContext;

/**
 * 登录验证控制模块
 * 
 * @author 演示
 *
 */

public class LoginServlet extends BaseServlet {

	private static final long serialVersionUID = 7279138098299110478L;
	private static final Logger LOG = LogManager.getLogger(LoginServlet.class);
	String aesKey = "ming";// 密码加密使用

	// 用户和Session绑定关系
	final Map<String, HttpSession> MAP1 = new HashMap<String, HttpSession>();
	// SessionId和用户的绑定关系
	final Map<String, String> MAP2 = new HashMap<String, String>();

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String m = request.getParameter("m");// 动作类型参数
		if ("web".equals(m)) {
			this.webLogin(request, response);
		} else if ("app".equals(m)) {
			this.AppLogin(request, response);
		} else if ("check".equals(m)) {
			this.checkUserOnline(request, response);
		}

	}

	private void webLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String path = "login.jsp";
		// LOG.info("用户登录");
		List<Object> urlDataList = new ArrayList<Object>();
		List<Object> menuDataList = new ArrayList<Object>();

		try {

			String userid = request.getParameter("userid");
			String pwd = request.getParameter("pwd");

			byte[] encrypt = PasswordUtil.AESEncrypt(pwd, aesKey);// 加密
			System.out.println("AES加密后-byte[]:" + encrypt);
			String strHex = PasswordUtil.parseByte2HexStr(encrypt);
			System.out.println("转换后的十六进制:" + strHex);
			pwd = strHex;

			User user = new User(userid, pwd);

			if (user == null) {
				request.setAttribute("error", "用户名或密码错误！");
				process(request, response, path);
			}
			// 根据用户名获取权限路径url
			for (Role role : user.getRoles()) {
				for (Menu menu : role.getMenus()) {
					urlDataList.add(menu.getUrl());
					session.setAttribute("urlDataList", urlDataList);
				}
			}

			session.setAttribute("agencode", user.getAgencode()); // 在session中设置登记员的行政区域编号
			session.setAttribute("userid", user.getFullname()); // 在session中设置用户

			this.handleSession(request, response, user);
			request.setAttribute("list", menuDataList);
			LOG.info(user.getFullname() + "登录成功了！！");
			path = "index.jsp";
		} catch (UserNotFoundException e) {
			// LOG.info(e.getMessage(),e);
			path = "login.jsp";
		}
		request.setAttribute("error", "用户名或密码错误！");
		// 跳转页面
		process(request, response, path);
	}

	private void AppLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		MobileApiEntity mobileApiEntity = new MobileApiEntity();
		try {
			String userid = req.getParameter("userid");
			String pwd = req.getParameter("pwd");
			User user = new User(userid, pwd);
			this.handleSession(req, resp, user);
			HttpSession session = req.getSession();
			session.setAttribute("agencode", user.getAgencode()); // 在session中设置登记员的行政区域编号
			session.setAttribute("userid", user.getFullname()); // 在session中设置用户

		} catch (Exception e) {
			mobileApiEntity.setCode(Constant.CODE_1002);
			mobileApiEntity.setError(Constant.VALUE_1002);
		}
		Appwrite(mobileApiEntity, req, resp);
	}

	/**
	 * 专门用于处理单点登录的方法，如果用户用同一个账号登录过了，将之前的session销毁。
	 * 
	 * @param request
	 */
	public void handleSession(HttpServletRequest request, HttpServletResponse response, User user) {

		if (user == null) {
			return;
		}
		// 作为区分用户的唯一标识。
		String usernameKey = "";

		// 如果用户名不为空
		if (!StringUtils.isEmpty(user.getUserid())) {
			usernameKey = user.getUserid();
		}

		// 获取session管理实例。
		MySessionContext myc = MySessionContext.getInstance();
		HttpSession httpSession = myc.checkExist(usernameKey);

		// 如果sessionMap中存在该用户标识的session，将前一个session关闭。
		if (httpSession != null) {
			httpSession.invalidate();

		}

		// 将代表用户的唯一标识，大部分是username,由于第三方登录，有时也是otherId,或者openId
		HttpSession sessionCurrent = request.getSession();
		sessionCurrent.setAttribute("usernameKey", usernameKey);

	}

	public void checkUserOnline(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		System.out.println("来到了checkUserOnline()方法");
		PrintWriter out = response.getWriter();
		out.print(session.getAttribute("msg"));
	}

}
